//
//  CustomKeyboard.m
//  YongChuanTradingArea
//
//  Created by 李冰 on 2017/9/15.
//  Copyright © 2017年 李冰. All rights reserved.
//

#import "CustomKeyboard.h"

@implementation CustomKeyboard

- (instancetype)initWithFrame:(CGRect)frame {

    if (self = [super initWithFrame:frame])
    {
        
        [self _initializeItems];
        self.backgroundColor = kWhiteColor;
    }
    
    return self;
}

- (void) _initializeItems {

    CGFloat W = AdaptationRatio(60);
    CGFloat H = W;
    CGFloat X = 0.0;
    CGFloat Y = 0.0;
    CGFloat xMargin = (lbScreenWidth - 4 * W) / 5.0f;
    CGFloat yMargin = (AdaptationRatio(335) - 4 * H) / 5.0f;
    
    NSInteger line = 0;
    
    UIButton *last = nil;
    int num = 1;
    for (int i = 0; i < 15; i++)
    {
        
        if (i % 4 == 0 && i != 0)
        {
            line++;
            last = nil;
        }
        
        X = last ? CGRectGetMaxX(last.frame) + xMargin : xMargin;
        Y = line * (H + yMargin) + yMargin;
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(X, Y, W, H)];
        button.layer.cornerRadius = AdaptationRatio(30);
        button.layer.borderColor = [UIColor colorWithHex:0xcccccc].CGColor;
        button.layer.borderWidth = 1;
        [button setTitleColor:kBlackColor forState:UIControlStateNormal];
        button.tag = i;
        [button addTarget:self action:@selector(didPressAction:) forControlEvents:UIControlEventTouchUpInside];
        if (i == 3)
        {
            [button setTitle:@"🔙" forState:UIControlStateNormal];
        }
        else if (i == 7)
        {
            [button setTitle:@"c" forState:UIControlStateNormal];
        }
        else if (i == 11)
        {
            [button setTitle:@"+" forState:UIControlStateNormal];
        }
        else if (i < 13)
        {
            [button setTitle:[NSString stringWithFormat:@"%d", num] forState:UIControlStateNormal];
            num++;
            if (num == 10) num = 0;
        }
        else if (i == 13)
        {
            [button setTitle:@"." forState:UIControlStateNormal];
        }
        else if (i == 14)
        {
            [button setTitleColor:kWhiteColor forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"btn_keypad"] forState:UIControlStateNormal];
            button.frame = CGRectMake(button.lb_x, button.lb_y, 2 * W + xMargin, H);
            button.layer.borderWidth = 0;
            button.layer.cornerRadius = 0;
            [button setTitle:@"扫码收款" forState:UIControlStateNormal];
        }
    
        [self addSubview:button];
        last = button;
        
    }
}

- (void) didPressAction:(UIButton *) sender {

    if ([self.delegate respondsToSelector:@selector(buttonDidPress:index:)])
    {
        [self.delegate buttonDidPress:sender index:sender.tag];
    }
}

@end
